<template>
  <div class="common-layout">
    <!-- 已登录状态 - 带侧边栏布局 -->
    <el-container v-if="isLoggedIn" class="logged-layout">
      <!-- 侧边栏 -->
      <el-aside width="220px" class="sidebar">
        <div class="sidebar-header">
          <el-avatar
            :src="userInfo?.avatar || defaultAvatar"
            class="user-avatar"
          >
            <i class="el-icon-user" v-if="!userInfo?.avatar"></i>
          </el-avatar>
          <div class="user-info">
            <p class="username">{{ userInfo?.username || "用户中心" }}</p>
            <p class="user-role">{{ isShangHu ? "普通用户" : "商户" }}</p>
          </div>
        </div>

        <el-menu
          :default-active="currentRoute"
          background-color="#2c3e50"
          text-color="#ecf0f1"
          active-text-color="#42b983"
          router
          class="main-menu"
          :unique-opened="true"
        >
          <el-menu-item index="/My/MyZhongXin" class="menu-item">
            <i class="el-icon-user-solid menu-icon"></i>
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="/My/MyOrders" class="menu-item">
            <i class="el-icon-shopping-cart menu-icon"></i>
            <span>我的订单</span>
          </el-menu-item>
           <el-menu-item index="/My/MyKan" class="menu-item">
            <i class="el-icon-shopping-cart menu-icon"></i>
            <span>我的砍价</span>
          </el-menu-item>
          <el-menu-item index="/My/MyCollection" class="menu-item">
            <i class="el-icon-star-off menu-icon"></i>
            <span>我的收藏</span>
          </el-menu-item>
          <el-menu-item index="/My/MyWantBuy" class="menu-item">
            <i class="el-icon-star-off menu-icon"></i>
            <span>我的预定</span>
          </el-menu-item>
           <el-menu-item index="/My/MyPurchase" class="menu-item">
            <i class="el-icon-star-off menu-icon"></i>
            <span>我的求购</span>
          </el-menu-item>
          <el-menu-item
            v-if="isShangHu"
            index="/My/MyShangHu"
            class="menu-item"
          >
            <i class="el-icon-office-building menu-icon"></i>
            <span>申请成为商户</span>
          </el-menu-item>
          <el-menu-item v-else index="/My/MyShangPing" class="menu-item">
            <i class="el-icon-goods menu-icon"></i>
            <span>商品详情</span>
          </el-menu-item>
        </el-menu>

        <div class="sidebar-footer">
          <el-button
            type="text"
            icon="el-icon-switch-button"
            class="logout-btn"
            @click="handleLogout"
          >
            退出登录
          </el-button>
        </div>
      </el-aside>

      <!-- 主内容区 -->
      <el-main class="main-content">
        <div class="content-header">
          <h2 class="page-title">{{ currentPageTitle }}</h2>
          <div class="header-actions">
            <el-breadcrumb separator="/" class="breadcrumb">
              <el-breadcrumb-item :to="{ path: '/My' }"
                >个人中心</el-breadcrumb-item
              >
              <el-breadcrumb-item>{{ currentPageTitle }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </div>
        <div class="content-body">
          <router-view></router-view>
        </div>
      </el-main>
    </el-container>

    <!-- 未登录状态 - 登录页面 -->
    <div v-else class="login-page">
      <div class="login-bg"></div>
      <el-container class="login-container">
        <el-main class="center-content">
          <el-card class="login-card" shadow="hover">
            <div class="login-header">
              <div class="logo-container">
                <i class="el-icon-shopping-bag header-icon"></i>
                <h2 class="system-name">商户管理系统</h2>
              </div>
              <h1 class="welcome-text">欢迎回来</h1>
              <p class="tip-text">请登录以继续访问系统</p>
            </div>

            <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
              round
              icon="el-icon-unlock"
            >
              立即登录
            </el-button>

            <div class="login-footer">
              <p class="copyright">© 2023 商户管理系统 版权所有</p>
            </div>
          </el-card>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";

// 路由实例
const router = useRouter();
const route = useRoute();

// 状态管理
const userInfo = ref(null);
const isLoggedIn = ref(false);
const isShangHu = ref(true);
const currentPageTitle = ref("个人信息");
const currentRoute = ref("/My/MyZhongXin");
const defaultAvatar =
  "https://cube.elemecdn.com/3/7c/3ea6beec64348a16670ae4b9bce1.jpeg";

// 页面标题映射表
const pageTitleMap = {
  "/My/MyZhongXin": "个人信息",
  "/My/MyOrders": "我的订单",
  "/My/MyCollection": "我的收藏",
  "/My/MyShangHu": "申请成为商户",
  "/My/MyShangPing": "商品详情",
};

// 监听路由变化更新页面标题和选中菜单
watch(
  () => route.path,
  (newPath) => {
    currentRoute.value = newPath;
    currentPageTitle.value = pageTitleMap[newPath] || "个人中心";
  },
  { immediate: true }
);

// 获取用户信息
function getUserInfo() {
  const storedUser = localStorage.getItem("counter");
  if (storedUser) {
    try {
      userInfo.value = JSON.parse(storedUser);
      if (userInfo.value.userId && userInfo.value.token) {
        isLoggedIn.value = true;
        getUserById();
        // 同步当前路由
        currentRoute.value = route.path;
      }
    } catch (error) {
      console.error("解析用户信息失败:", error);
      localStorage.removeItem("counter"); // 清除错误数据
      ElMessage.error("用户信息异常，请重新登录");
    }
  } else {
    userInfo.value = null;
    isLoggedIn.value = false;
  }
}

// 验证用户是否为商户
async function getUserById() {
  if (isLoggedIn.value) {
    try {
      const userId = userInfo.value.userId;
      const res = await axios.get(
        `/eduservice/sellerQualification/getUseId/${userId}`
      );
      isShangHu.value = res.data === "" ? true : false;
    } catch (error) {
      console.error("获取商户信息失败:", error);
      isShangHu.value = true; // 出错时默认按普通用户处理
      ElMessage.warning("获取用户权限失败，默认按普通用户显示");
    }
  }
}

// 登录跳转
function handleLogin() {
  router.push("/Login");
}

// 退出登录
function handleLogout() {
  localStorage.removeItem("counter");
  isLoggedIn.value = false;
  userInfo.value = null;
  ElMessage.success("退出登录成功");
  setTimeout(() => {
    router.push("/Login");
  }, 500);
}

// 初始化
onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
/* 基础样式重置 */
:deep(*) {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 已登录布局 */
.logged-layout {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 侧边栏样式 */
.sidebar {
  background-color: #2c3e50;
  color: #ecf0f1;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.user-info {
  overflow: hidden;
}

.username {
  font-size: 16px;
  font-weight: 500;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.user-role {
  font-size: 12px;
  color: #bdc3c7;
  margin-top: 4px;
}

.main-menu {
  flex: 1;
  padding-top: 15px !important;
}

.menu-item {
  height: 50px !important;
  line-height: 50px !important;
  margin-bottom: 5px !important;
  transition: all 0.2s ease !important;
}

.menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.menu-icon {
  margin-right: 12px !important;
  font-size: 18px !important;
}

.sidebar-footer {
  padding: 15px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.logout-btn {
  width: 100%;
  color: #ecf0f1 !important;
  justify-content: center !important;
  transition: all 0.2s ease !important;
}

.logout-btn:hover {
  color: #e74c3c !important;
  background-color: rgba(231, 76, 60, 0.1) !important;
}

/* 主内容区样式 */
.main-content {
  padding: 20px !important;
  overflow-x: hidden;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-title {
  font-size: 22px;
  color: #2c3e50;
  font-weight: 600;
}

.breadcrumb {
  font-size: 14px;
  color: #7f8c8d;
}

.content-body {
  background-color: #fff;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  min-height: calc(100vh - 160px);
}

/* 未登录页面样式 */
.login-page {
  position: relative;
  min-height: 100vh;
  overflow: hidden;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
  z-index: 1;
}

.login-bg::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.05'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}

.login-container {
  position: relative;
  z-index: 2;
  min-height: 100vh;
}

.center-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  padding: 20px;
}

.login-card {
  width: 420px;
  padding: 40px 30px;
  border-radius: 12px;
  background-color: #fff;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.login-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.header-icon {
  font-size: 70px;
  color: #3498db;
  margin-bottom: 15px;
  transition: transform 0.3s ease;
}

.login-card:hover .header-icon {
  transform: scale(1.1) rotate(5deg);
}

.system-name {
  font-size: 20px;
  color: #2c3e50;
  font-weight: 600;
}

.welcome-text {
  color: #2c3e50;
  font-size: 26px;
  margin-bottom: 12px;
  font-weight: 500;
}

.tip-text {
  color: #7f8c8d;
  font-size: 14px;
  margin-bottom: 35px;
  line-height: 1.6;
}

.login-btn {
  width: 85%;
  height: 48px;
  font-size: 16px;
  letter-spacing: 1px;
  background-color: #3498db;
  border-color: #3498db;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background-color: #2980b9;
  border-color: #2980b9;
  transform: translateY(-3px);
  box-shadow: 0 8px 15px rgba(52, 152, 219, 0.3);
}

.login-footer {
  margin-top: 40px;
}

.copyright {
  font-size: 12px;
  color: #95a5a6;
  text-align: center;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .sidebar {
    width: 60px !important;
  }

  .user-info,
  .menu-item span,
  .sidebar-footer span {
    display: none;
  }

  .sidebar-header {
    justify-content: center;
    padding: 15px 0;
  }

  .menu-icon {
    margin-right: 0 !important;
    font-size: 20px !important;
  }

  .content-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .login-card {
    width: 100%;
    max-width: 350px;
  }
}
</style>